package com.lry.basic.jvm.asm.transform_class.demo4;

import aj.org.objectweb.asm.ClassVisitor;
import aj.org.objectweb.asm.FieldVisitor;

public class AddFieldVisitor extends ClassVisitor {
    private final int fieldAccess;
    private final String fieldName;
    private final String fieldDesc;

    private boolean isFieldPresent;

    public AddFieldVisitor(int api, ClassVisitor cv,int fieldAccess, String fieldName, String fieldDesc) {
        super(api,cv);
        this.fieldAccess = fieldAccess;
        this.fieldDesc = fieldDesc;
        this.fieldName = fieldName;
    }


    @Override
    public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) {
        if (name.equals(fieldName)) {
            isFieldPresent = true;
        }
        return super.visitField(access, name, descriptor, signature, value);
    }

    @Override
    public void visitEnd() {
        if(!isFieldPresent){
            FieldVisitor fv = cv.visitField(fieldAccess,fieldName,fieldDesc,null,null);
            if(fv!=null)
                fv.visitEnd();
        }
        super.visitEnd();
    }
}
